package com.edu.dao.impl;

import com.edu.beans.Guest;
import com.edu.dao.GuestDao;
import com.edu.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class GuestDaoImpl implements GuestDao {

    QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());

    @Override
    public List<Guest> getGuestsByPhone(String phone) {
        try {
            String sqlAll = "select " +
                    "tb_books.id as id, " +  // 映射到 Guest.id（书籍ID）
                    "tb_vip.id as vipId, " +  // 映射到 Guest.vipId（会员ID）
                    "tb_vip.name as name, " +
                    "tb_vip.sex as sex, " +
                    "tb_vip.card as card, " +
                    "tb_vip.phone as phone, " +
                    "tb_books.entertime as enterTime, " +
                    "tb_books.exittime as exitTime, " +
                    "tb_home.id as homeId, " +  // 映射到 Guest.homeId（房间ID）
                    "tb_home.h_type as h_Type, " +
                    "tb_home.num as num " +
                    "from tb_books, tb_vip, tb_home " +
                    "where tb_books.vip_id = tb_vip.id " +
                    "and tb_books.home_id = tb_home.id";

            if (phone == null || phone.trim().equals("")) {
                return qr.query(sqlAll, new BeanListHandler<>(Guest.class));
            } else {
                String sqlByPhone = sqlAll + " and tb_vip.phone like ?";
                return qr.query(sqlByPhone, new BeanListHandler<>(Guest.class), "%" + phone + "%");
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询住客信息失败", e);
        }
    }
}
